<template>
  <div class="data-dict">
    <unfold>
      <!-- 左侧组名称列表 -->
      <template v-slot:tree-list>
        <div class="left box">

          <!-- header -->
          <div class="box-header bg-primary text-white text-weight-regular flex items-center">
            <q-icon name="iconfont icontubiao-85" color="white" class="q-mr-sm" />
            <div class="head-title vertical-middle user-select-none">组名称</div>
          </div>

          <!-- 列表 -->
          <q-scroll-area class="box-content bg-white" :thumb-style="CommonConfig.thumbStyle">
            <q-list style="min-width: 100px;">
              <div v-for="dictionaryGroup in dictionaryGroups" :key="dictionaryGroup.code">
                <q-item
                  class="role-item"
                  :active="selectedRoleId === dictionaryGroup.code"
                  active-class="activated"
                  @click="onRoleClick(dictionaryGroup.code)"
                  clickable
                  v-ripple
                >
                  <q-item-section>{{ dictionaryGroup.label }}</q-item-section>
                </q-item>
                <q-separator />
              </div>
            </q-list>
          </q-scroll-area>
        </div>
      </template>

      <!-- 右侧 card -->
      <template v-slot:content>
        <div class="right box right-content">
          <div class="relative-position full-height page-content">
            <div class="form-inline" style="width: 100%">
              <q-btn class="margin-r-10 margin-t-20" outline color="primary" label="新增" @click="openAddDialog" />
            </div>
            <q-table
                :pagination = "pagination"
                class="myTable scroll stick-last-col margin-b-20"
                :columns="columns"
                :data="tableData"
                :loading="isTableLoading"
                style="margin-bottom: 62px"
                row-key="id"
                flat
                :hide-bottom="!!tableData.length"
                no-data-label="暂无数据"
              >
                <template v-slot:body="props">
                  <q-tr :props="props">
<!--                    <q-td key="gname" :props="props">{{ props.row.gname }}</q-td>-->
                    <q-td key="index" :props="props">{{ props.row.index }}</q-td>
                    <q-td key="label" :props="props">{{ props.row.label }}</q-td>
                    <q-td key="value" :props="props">{{ props.row.value }}</q-td>
                    <q-td key="remark" :props="props">{{ props.row.remark !== '' ? props.row.remark : '--' }}</q-td>
                    <q-td key="customerFlag" :props="props">{{ props.row.customerFlag ? '是(可删除)' : '否(不可删除)' }}</q-td>
                    <q-td class="dict-status">
                      <div
                        class="indicator"
                        :class="{
                          negative: props.row.enableFlag === false,
                          positive: props.row.enableFlag === true
                        }">
                        </div>
                        <span
                          class="text"
                          :class="{
                    negative: props.row.enableFlag === false,
                    positive: props.row.enableFlag === true
                  }"
                        >
                  {{ props.row.enableFlagName }}
                </span>
                  </q-td>
                  <q-td class="operations" style="text-align: center; width: 160px">
                    <div class="btn-group">
<!--                      <table-btn btnType="other" icon="icontubiao-88" tooltip="上移" @click="moveUp(props.row)" :disabled="disableMoveUp(props.row)"/>-->
<!--                      <table-btn btnType="other" icon="icontubiao-87" tooltip="下移" @click="moveDown(props.row)" :disabled="disableMoveDown(props.row)"/>-->
                      <table-btn btnType="edit" @click="openEditDialog(props.row)"/>
                      <table-btn btnType="delete" :disabled="disabledDel(props.row)" @click="onDeleteClick(props.row.id)" tips="确定要删除此项吗？"/>
                      <q-toggle
                        v-model="props.row.enableFlag"
                        :true-value="statusToggleTrueVal"
                        :false-value="statusToggleFalseVal"
                        checked-icon="iconfont icontubiao-49"
                        unchecked-icon="iconfont icontubiao-48"
                        :disable="isStatusToggleDisabled[props.row.id]"
                        color="positive"
                        @input="onStatusToggle(props.row, $event)"
                      >
                        <template v-slot>
                          <q-tooltip>{{ getStatusToggleTip(props.row.enableFlag) }}</q-tooltip>
                        </template>
                      </q-toggle>
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
            <pagination v-model="pagination.page"
                        :page-size="pagination.rowsPerPage"
                        :total="pagination.rowsNumber"
                        @changePageSize="onPageSizeChange"
                        @changePage="onPageChange"
                        style="margin-bottom: 20px" />
          </div>
        </div>
      </template>
    </unfold>

    <add-dialog
    ref="dict"
    :show="dialog.show"
    :state="dialog.title"
    :dictionaryGroup = "dialog.dictionaryGroup"
    :dictionaryGroupCode= "dialog.dictionaryGroupCode"
    @close="dialog.show = false"
    @submit="submit"
    />
  </div>
</template>

<script>
import {
  getDictionaryGroup,
  changeEnable,
  move,
  deleteDictionaryList,
  addDictionaryList,
  editDictionaryList,
  getDictList
} from 'src/boot/system/data-dict'
import Unfold from 'src/components/unfold'
import AddDialog from './components/add-edit-data-dict'
import _ from 'lodash'
import Pagination from 'src/components/pagination'
export default {
  name: 'data-dict',
  components: {
    Unfold,
    AddDialog,
    Pagination
  },
  data () {
    return {
      dialog: {
        title: '', // 新增_编辑对话框的标题
        show: false, // 新增_编辑对话框显示_隐藏标识
        dictionaryGroup: '',
        dictionaryGroupCode: ''
      },
      isTableLoading: false, // 数据信息列表loading
      tableData: [], // 数据信息列表数据源
      dictionaryGroups: [], // 字典组
      statusToggleTrueVal: true, // 状态 toggle 为 true 时的 status 值
      statusToggleFalseVal: false, // 状态 toggle 为 false 时的 status 值
      selectedRoleId: null, // 选择的字典组
      isStatusToggleDisabled: {}, // 避免用户操作过快
      // 使分页每页显示无限条
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      // 表格列标
      columns: [
        // { name: 'gname', field: 'gname', label: '字典组', align: 'left' },
        { name: 'index', field: 'index', label: '序号', align: 'left' },
        { name: 'label', field: 'label', label: '内容', align: 'left' },
        { name: 'value', field: 'value', label: '值', align: 'left' },
        { name: 'remark', field: 'remark', label: '备注', align: 'left' },
        { name: 'customerFlag', field: 'customerFlag', label: '是否自定义', align: 'left' },
        { name: 'enableFlagName', field: 'enableFlagName', label: '是否可用', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ]
    }
  },
  created () {
    this.listLictionaryGroups()
  },
  methods: {

    // 初始化字典组数据
    listLictionaryGroups () {
      getDictionaryGroup().then(res => {
        this.dictionaryGroups = res
        return res[0].code
      }).then(code => {
        this.selectedRoleId = code
        this.getList()
      })
    },

    // 点击字典组列表
    onRoleClick (code) {
      this.selectedRoleId = code
      this.pagination.page = 1
      this.getList()
    },
    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getList()
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange (val) {
      this.pagination.page = val
      this.getList()
    },

    // 获取字典项列表
    getList () {
      this.isTableLoading = true
      const params = {
        pageNum: this.pagination.page,
        pageSize: this.pagination.rowsPerPage
      }
      getDictList(this.selectedRoleId, params).then(res => {
        if (res.list.length) {
          res.list.forEach((i, index) => {
            i.index = index + 1 + (this.pagination.page - 1) * this.pagination.rowsPerPage
            i['enableFlagName'] = (i['enableFlag'] === false || i['enableFlag'] === '0') ? '禁用' : '启用'
          })
        }
        this.pagination.rowsNumber = res.total
        this.tableData = res.list
      }).finally(() => {
        this.isTableLoading = false
      })
    },

    // 切换字典项禁用/启用状态
    onStatusToggle (val, status) {
      status ? status = 1 : status = 0
      this.$set(this.isStatusToggleDisabled, val.id, true)
      changeEnable(status, val.id, this.selectedRoleId).then(() => {
        this.getList()
      }).finally(() => {
        this.$set(this.isStatusToggleDisabled, val.id, false)
      })
    },

    // 根据字典项启禁用推算toogle组件tooptip提示文字
    getStatusToggleTip (val) {
      return val ? '禁用' : '启用'
    },
    // 向上移动字典项
    moveUp (row) {
      this.moveToList(row.id, 'up')
    },

    // 项下移动字典项
    moveDown (row) {
      this.moveToList(row.id, 'down')
    },
    // 上移下移公共方法
    moveToList (id, type) {
      let index = _.findIndex(this.tableData, { id })
      let nextIndex = type === 'up' ? index - 1 : index + 1
      let nextId = _.get(this.tableData[nextIndex], 'id')
      // 上移-1 下移+1
      move(id, nextId, this.selectedRoleId).then(() => {
        this.$message.success('移动成功')
        this.getList()
      })
    },
    // 向上移动按钮的条件禁用
    disableMoveUp ({ id }) {
      return !_.findIndex(this.tableData, { id })
    },

    disabledDel (row) {
      return !row.customerFlag
    },

    // 向下移动按钮的条件禁用
    disableMoveDown ({ id }) {
      return _.findIndex(this.tableData, { id }) === this.tableData.length - 1
    },

    // 删除字典项
    onDeleteClick: function (id) {
      deleteDictionaryList(id, this.selectedRoleId).then(res => {
        if (res.code === '1200') {
          if (this.tableData.length <= 1) {
            this.pagination.page = this.pagination.page !== 1 ? this.pagination.page - 1 : 1
          }
          this.$message.success('删除成功')
          this.getList()
        }
      })
    },

    // 判断选中的字典组列表code与label为传递给新增_编辑对话框准备数据

    filterDict () {
      for (const i of this.dictionaryGroups) {
        if (i['code'] === this.selectedRoleId) {
          this.dialog.dictionaryGroup = i['label']
          this.dialog.dictionaryGroupCode = i['code']
        }
      }
    },

    // 打开新增字典项窗口
    openAddDialog () {
      this.$refs.dict.reset()
      this.dialog.show = true
      this.dialog.title = 'add'
      this.filterDict()
    },

    // 打开编辑字典项窗口
    openEditDialog (row) {
      this.dialog.show = true
      this.dialog.title = 'edit'
      this.filterDict()
      this.$refs.dict.assignment(row)
    },

    // 提交表单
    submit (state, val) {
      const query = { ...val }
      query.enable = val.enable ? 1 : 0
      if (state === 'add') {
        addDictionaryList(query).then(res => {
          this.dialog.show = false
          if (res.code === '1200') {
            this.getList()
            this.$message.success('添加成功')
          }
        })
      } else {
        editDictionaryList(query).then(res => {
          this.dialog.show = false
          if (res.code === '1200') {
            this.getList()
            this.$message.success('编辑成功')
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="stylus">
  .condition {
    width: 100%
    /*height: 40px*/
    margin-bottom 20px
    margin-top 20px
    margin-left 30px
  }
  .dict-status {
    .indicator {
      display inline-block
      border-radius 50%
      height 10px
      width 10px
      margin-right 2px

      &.positive {
        background $positive
      }

      &.negative {
        background $negative
      }
    }

    .text {
      &.positive {
        color $positive
      }

      &.negative {
        color $negative
      }
    }

  }
  .data-dict {
    .box {
      display flex
      flex-direction column
      width 100%
      min-width 250px
      border-radius 6px
      overflow hidden
      height 100%

      .box-header {
        flex 40px 0
        padding 0 20px
        line-height 40px
        font-size 14px
        .head-title{
          font-weight bold
        }
      }

      &.left {
        .box-content {
          flex 1
          padding-bottom 20px

          .role-item {
            padding-left 30px
            font-size 14px

            &.activated {
              background #cfd6fe
              color $primary
            }

            &:hover {
              background #e8ebff

              /deep/ .q-focus-helper {
                display none
              }
            }
          }

          .q-separator {
            margin-left 20px
            width calc(100% - 40px)
          }
        }
      }

      &.right {
        .box-content {
          display flex
          flex-direction column
          flex 1
          padding-top 0

          .table-header {
            display flex
            justify-content space-between
            align-items center
            padding 0 16px 0 40px
            height 48px
            background #F3F3F3
            margin-top 30px

            &__right {
              display flex

              .table-header__item {
                padding-right 10px

                header-items-sparsity-s() {
                  &.type {
                    min-width 60px
                  }

                  &.parentMenu {
                    min-width 140px
                  }

                  &.toggle {
                    min-width 70px
                  }
                }

                header-items-sparsity-m() {
                  &.type {
                    min-width 100px
                  }

                  &.parentMenu {
                    min-width 220px
                  }

                  &.toggle {
                    min-width 104px
                  }
                }

                header-items-sparsity-m()

                @media screen and (min-width 1024px) and (max-width 1200px) {
                  header-items-sparsity-s()
                }

                @media screen and (max-width 1000px) {
                  header-items-sparsity-s()
                }
              }
            }
          }

          .menu-item-box {
            width 100%
            display flex
            justify-content space-between
            align-items center

            .wrapper {
              padding-right 10px
            }

            .right-box {
              display flex
              align-items center

              .wrapper {
                boxes-sparsity-s() {
                  &.type, &.toggle {
                    min-width 60px
                  }

                  &.parent-name {
                    min-width 140px
                  }
                }

                boxes-sparsity-m() {
                  &.type, &.toggle {
                    min-width 100px
                  }

                  &.parent-name {
                    min-width 220px
                  }
                }

                boxes-sparsity-m()

                @media screen and (min-width 1024px) and (max-width 1200px) {
                  boxes-sparsity-s()
                }

                @media screen and (max-width 1000px) {
                  boxes-sparsity-s()
                }
              }
            }
          }
        }
      }
    }
  }
</style>

<style lang="stylus">
  .data-dict{
    .myTable .q-table__middle{
      max-height calc(100%)
    }
  }
</style>
